package com.runshu.newsmartark.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jcraft.jsch.UserInfo;
import com.runshu.newsmartark.R;
import com.runshu.newsmartark.adapter.NewProDtaAdapter;
import com.runshu.newsmartark.adapter.TakeStockAdapter;
import com.runshu.newsmartark.base.MyApplication;
import com.runshu.newsmartark.base.TakeStockBase;
import com.runshu.newsmartark.dbutil.DBUtils;
import com.runshu.newsmartark.dbutil.LogListEntity;
import com.runshu.newsmartark.dbutil.ProAllDao;
import com.runshu.newsmartark.dbutil.ProAllEntity;
import com.runshu.newsmartark.entity.CategoryListEntity;
import com.runshu.newsmartark.entity.CheckInventoryEntity;
import com.runshu.newsmartark.entity.ConfirmStockEntity;
import com.runshu.newsmartark.entity.HwInfoUtils;
import com.runshu.newsmartark.entity.InventoryListEntity;
import com.runshu.newsmartark.entity.MqttBean;
import com.runshu.newsmartark.entity.NewTakeStockEntity;
import com.runshu.newsmartark.entity.ProductsBean;
import com.runshu.newsmartark.entity.UserInfoEntity;
import com.runshu.newsmartark.event.BindEventBus;
import com.runshu.newsmartark.event.Event;
import com.runshu.newsmartark.event.EventBusUtils;
import com.runshu.newsmartark.event.EventCode;
import com.runshu.newsmartark.mvp.contract.ConfirmStockContract;
import com.runshu.newsmartark.mvp.contract.ProductTypeDtaContract;
import com.runshu.newsmartark.mvp.contract.ProductsByCategoryContract;
import com.runshu.newsmartark.mvp.model.ConfirmStockModel;
import com.runshu.newsmartark.mvp.model.ProductTypeDtaModel;
import com.runshu.newsmartark.mvp.model.ProductsByCategoryModel;
import com.runshu.newsmartark.mvp.presenter.ConfirmStockPresenter;
import com.runshu.newsmartark.mvp.presenter.ProductTypeDtaPresenter;
import com.runshu.newsmartark.mvp.presenter.ProductsByCategoryPresenter;
import com.runshu.newsmartark.network.netbean.ResponseBean;
import com.runshu.newsmartark.smartbox.SmartBoxHelper;
import com.runshu.newsmartark.util.CountDownTimer;
import com.runshu.newsmartark.util.MacUtils;
import com.runshu.newsmartark.util.NetStatusUtils;
import com.runshu.newsmartark.util.NetUtils;
import com.runshu.newsmartark.util.RecyclerViewNoBugLinearLayoutManager;
import com.runshu.newsmartark.util.RefUtil;
import com.runshu.newsmartark.util.SoundPoolUtils;
import com.runshu.newsmartark.util.common.LogUtil;
import com.runshu.newsmartark.util.common.ToastUtils;
import com.runshu.newsmartark.util.widget.CommonShowDialog;
import com.runshu.newsmartark.util.widget.TopTitleBar;
import com.zxl.library.DropDownMenu;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.runshu.newsmartark.util.StringUtils.sdf;

/**
 * Demo class
 *
 * @author yu
 * @date 2020/8/26
 * @decs：
 */
@BindEventBus
public class TakeStockDtaActivity extends TakeStockBase implements ProductsByCategoryContract.View, ConfirmStockContract.View, ProductTypeDtaContract.View {
    private static final String TAG = "TakeStockDtaActivity";
    @BindView(R.id.tvTimer)
    TextView tvTimer;
    @BindView(R.id.toolbar)
    TopTitleBar mToolbar;
    @BindView(R.id.tv_all_num)
    TextView mTvAllNum;
    @BindView(R.id.bt_gm)
    TextView bt_gm;
    @BindView(R.id.rela_root)
    RelativeLayout mRelaRoot;
    @BindView(R.id.dropDownMenu)
    DropDownMenu mDropDownMenu;
    @BindView(R.id.bt_openDoor)
    TextView btOpenDoor;
    private List<InventoryListEntity.ListBean> mData;
    private NewProDtaAdapter mAdapter;
    private ProductsByCategoryPresenter productsPresenter;
    private ConfirmStockPresenter confirmStockPresenter;
    private ProductTypeDtaPresenter typeDtaPresenter;
    private CommonShowDialog commonShowDialog;
    private boolean isCloseDoor = true;
//    private MTagRealList mTagRealList;

    //标识重新盘点用
    private String type;
    private List<CategoryListEntity> categoryList;
    private List<CategoryListEntity> ManufacturerSelList;
    private List<CategoryListEntity> ModelSelList;

    private boolean isLoadMore = false;
    private int pageSize = 20;
    private int pageNum = 1;
    private String categoryValue, stockName, model, manufacturer;
    private String macAddress;
    private String headers[] = {"产品类别", "产品规格", "生产厂家"};
    private String selectTypeOne[] = {};
    private String selectTypeTwo[] = {};
    private String selectTypeThree[] = {};
    private int[] types = new int[]{DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_LIST_CITY, DropDownMenu.TYPE_LIST_CITY};
    private SwipeRefreshLayout mSwipeLayout;
    private RecyclerView mRecyStock;
    private View contentView;
    private int expiryDate, stockNameID;
    private boolean isPanMode;
    private Intent intent;
    private boolean isOperation;
    private int closeTime;
    private CountDownTimer timercloseDia;

    @Override
    protected int getLayoutId() {
        return R.layout.act_take_stock;
    }

    @Override
    protected void initView() {
        isOperation = MainActivity.isOperation;
        if (isOperation) {
            closeTime = MainActivity.dckmsjTime[MainActivity.dckmsj];
        } else {
            closeTime = 5000;
        }
        intent = getIntent();
        isPanMode = intent.getBooleanExtra("isPanMode", false);
        stockName = HwInfoUtils.getHwId(context);
        contentView = getLayoutInflater().inflate(R.layout.content_allpro_dta, null);
        mSwipeLayout = contentView.findViewById(R.id.swipe_layout);
        mRecyStock = contentView.findViewById(R.id.recy_all_pro);
        macAddress = MacUtils.getFormatMacAddr();
        categoryList = new ArrayList<>();
        ManufacturerSelList = new ArrayList<>();
        ModelSelList = new ArrayList<>();
//        mTagRealList = new MTagRealList();
        productsPresenter = new ProductsByCategoryPresenter(this, new ProductsByCategoryModel());
        confirmStockPresenter = new ConfirmStockPresenter(this, new ConfirmStockModel());
        mToolbar.setIsShowBac(false);

        if (isPanMode) {
            btOpenDoor.setText("盘点完成");
        } else {
            btOpenDoor.setText("重新开门");
        }

        if (isOperation) {
            bt_gm.setText("手术结束");
            mToolbar.setTitle("手术中");
            mToolbar.setTopBarBackground(getResources().getColor(R.color.color_F33938));
            bt_gm.setBackgroundColor(getResources().getColor(R.color.color_F33938));
        } else {
            mToolbar.setTitle("盘点");
            mToolbar.setTopBarBackground(getResources().getColor(R.color.colorPrimaryDark));
            bt_gm.setText("解除常开");
            bt_gm.setBackgroundColor(getResources().getColor(R.color.color_1DD483));
        }
        mData = new ArrayList<>();
        mAdapter = new NewProDtaAdapter(mData);
        mRecyStock.setLayoutManager(new RecyclerViewNoBugLinearLayoutManager(context));
        mRecyStock.setAdapter(mAdapter);
        mAdapter.bindToRecyclerView(mRecyStock);
        mAdapter.setEmptyView(R.layout.empty_view);
        typeDtaPresenter = new ProductTypeDtaPresenter(this, new ProductTypeDtaModel());
//        SoundPoolUtils.play(context, R.raw.raw_opean, 0);


    }

    @OnClick(R.id.bt_gm)
    public void onClickView(View v) {
        closeDoorHandler.removeMessages(0);
        closeDoorHandler.sendEmptyMessageDelayed(0, 0);
        if (isOperation) {
            bt_gm.setText("请关门");
        } else {
            bt_gm.setText("请关门");
        }

        bt_gm.setClickable(false);
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        mDropDownMenu.setFocusableInTouchMode(true);
        mDropDownMenu.requestFocus();
        mDropDownMenu.setOnKeyListener((v, keyCode, event) -> {
            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) {
                //退出activity前关闭菜单
                if (mDropDownMenu.isShowing()) {
                    mDropDownMenu.closeMenu();
                    return true;
                } else {
                    return false;
                }
            }
            return false;
        });
    }


    ArrayList<String> str = new ArrayList<>();

    @Override
    public void onScanResult(List<HashMap<String, String>> lsTagList, boolean fromCloseDoor, long a, long b) {
        super.onScanResult(lsTagList, fromCloseDoor);
        if (commonShowDialog != null) {
//            commonShowDialog.setContentHint("已盘点" + lsTagList.size() + "件" + '\n' + "B面用时===" + b + '\n' + "A面用时===" + a);
            commonShowDialog.setContentHint("已盘点" + lsTagList.size() + "件");
        }
        if (str == null) str = new ArrayList<>();
        str.clear();
        for (int i = 0; i < lsTagList.size(); i++) {
            str.add(RefUtil.decryptRfid(lsTagList.get(i).get("epc").replace(" ", "")));
        }
        if (NetStatusUtils.isConnected(context)) {
            confirmStockPresenter.checkInventory(HwInfoUtils.getCustomerId(context), HwInfoUtils.getHospitalId(context), macAddress, str, 0);

        } else {
            if (str.size()>0){
                LogListEntity logListEntity = new LogListEntity();
                String createTime = sdf.format(new Date());
                logListEntity.setCreateTime(createTime);
                logListEntity.setRfid(str);
                logListEntity.setUserCode(MyApplication.getUserInfoGlob().getUserCode());
                DBUtils.getInstance().getProAllDao().insertLogList(logListEntity);
            }


            if (commonShowDialog != null && commonShowDialog.isShowing()) {
                commonShowDialog.dismiss();
                commonShowDialog.closeLoding();
                EventBusUtils.sendEvent(new Event(EventCode.NetError));
                Intent intent = new Intent(context, MainActivity.class);
                startActivity(intent);
                EventBusUtils.sendEvent(new Event(EventCode.showExitDia));

            }

        }


    }


    @Override
    protected void initData() {
//        typeDtaPresenter.getCategoryList(macAddress, 1);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Map<String, String> CategoryMap = new HashMap<>();
                Map<String, String> ManufacturersMap = new HashMap<>();
                Map<String, String> ModleMap = new HashMap<>();
                List<ProAllEntity> selfProList = DBUtils.getInstance().getProAllDao().getSelfProList();
                for (int i = 0; i < selfProList.size(); i++) {
                    if (!(selfProList.get(i).getCategoryLevel2Name().equals("-") || selfProList.get(i).getCategoryLevel2Name().equals(""))) {
                        CategoryMap.put(selfProList.get(i).getCategoryLevel2Name(), selfProList.get(i).getCategoryLevel2());
                    }
                    if (!(selfProList.get(i).getVendorName().equals("-") || selfProList.get(i).getVendorName().equals(""))) {
                        ManufacturersMap.put(selfProList.get(i).getVendorName(), selfProList.get(i).getProductVendor());
                    }
                    if (!(selfProList.get(i).getRegularModel().equals("-") || selfProList.get(i).getRegularModel().equals(""))) {
                        ModleMap.put(selfProList.get(i).getRegularModel(), selfProList.get(i).getRegularModel());
                    }
                }

                categoryList.add(new CategoryListEntity("全部", ""));
                for (String key : CategoryMap.keySet()) {
                    CategoryListEntity categoryListEntity = new CategoryListEntity();
                    categoryListEntity.setLabel(key);
                    categoryListEntity.setValue(CategoryMap.get(key));
                    categoryList.add(categoryListEntity);
                }

                ManufacturerSelList.add(new CategoryListEntity("全部", ""));
                for (String key : ManufacturersMap.keySet()) {
                    CategoryListEntity categoryListEntity = new CategoryListEntity();
                    categoryListEntity.setLabel(key);
                    categoryListEntity.setValue(ManufacturersMap.get(key));
                    ManufacturerSelList.add(categoryListEntity);
                }

                ModelSelList.add(new CategoryListEntity("全部", ""));
                for (String key : ModleMap.keySet()) {
                    CategoryListEntity categoryListEntity = new CategoryListEntity();
                    categoryListEntity.setLabel(key);
                    categoryListEntity.setValue(ModleMap.get(key));
                    ModelSelList.add(categoryListEntity);
                }
                List<String> categoryStrings = new ArrayList<>();
                for (CategoryListEntity categoryListEntity : categoryList) {
                    categoryStrings.add(categoryListEntity.getLabel());
                }
                selectTypeOne = categoryStrings.toArray(new String[categoryStrings.size()]);

                List<String> ManufacStrings = new ArrayList<>();
                for (CategoryListEntity categoryListEntity : ManufacturerSelList) {
                    ManufacStrings.add(categoryListEntity.getLabel());
                }
                selectTypeThree = ManufacStrings.toArray(new String[ManufacStrings.size()]);
                List<String> ModelStrings = new ArrayList<>();
                for (CategoryListEntity categoryListEntity : ModelSelList) {
                    ModelStrings.add(categoryListEntity.getLabel());
                }
                selectTypeTwo = ModelStrings.toArray(new String[ModelStrings.size()]);
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        mDropDownMenu.setDropDownMenu(Arrays.asList(headers), initViewData(), contentView);
                    }
                });
//                closeDoor( 4000 );
                if (!isPanMode) {
                    closeDoorHandler.sendEmptyMessageDelayed(0, closeTime);
                    startCountDownTimer();
                }
            }
        }).start();
    }

    Handler closeDoorHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            closeDoor(100);
            return true;
        }
    });

    @Override
    public void onCloseDoor() {
        super.onCloseDoor();
        showJieSuanDia();
    }

    @Override
    protected void bindListener() {
        mAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                Intent intent = new Intent(context, ProDetailActivity.class);
//                intent.putExtra("manufacturer", mAdapter.getData().get(position).getProductVendor());
//                intent.putExtra("productNo", mAdapter.getData().get(position).getProductNo());
                intent.putExtra("model", mAdapter.getData().get(position).getGoodsModel());
                intent.putExtra("stockNameID", stockNameID);
                intent.putExtra("stockName", stockName);
//                intent.putExtra("expiryDate", expiryDate);
                intent.putExtra("productName", mAdapter.getData().get(position).getGoodsName());
                intent.putExtra("goodsId", mAdapter.getData().get(position).getGoodsId());
                intent.putExtra("type", 1);
                startActivity(intent);

            }
        });


        mSwipeLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                isLoadMore = false;
                pageNum = 1;//设为默认加载第一页
                mData.clear();
                productsPresenter.getInventoryList(HwInfoUtils.getCustomerId(context), HwInfoUtils.getHospitalId(context), stockName, pageSize, pageNum);

            }
        });
        mAdapter.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                isLoadMore = true;
                productsPresenter.getInventoryList(HwInfoUtils.getCustomerId(context), HwInfoUtils.getHospitalId(context), stockName, pageSize, pageNum);
//                productsPresenter.getProDta(mac, categoryValue, stockName, model, manufacturer, expiryDate, 0, pageSize, pageNum);
            }
        });
        mSwipeLayout.setRefreshing(true);
        mSwipeLayout.post(() -> {
            productsPresenter.getInventoryList(HwInfoUtils.getCustomerId(context), HwInfoUtils.getHospitalId(context), stockName, pageSize, pageNum);

        });

        //该监听回调只监听默认类型，如果是自定义view请自行设置，参照demo
        mDropDownMenu.addMenuSelectListener((index, pos, clickstr) -> {
            //index:点击的tab索引，pos：单项菜单中点击的位置索引，clickstr：点击位置的字符串
            LogUtil.e(TAG, "===index==" + index + "pos====" + pos);
            if (index == 0) {
                categoryValue = categoryList.get(pos).getValue();
                if (pos == 0) {
                    mDropDownMenu.setTabText(0, "产品类别");
                }
            } else if (index == 1) {
                model = ModelSelList.get(pos).getValue();
                if (pos == 0) {
                    mDropDownMenu.setTabText(1, "产品规格");
                }
            } else {
                manufacturer = ManufacturerSelList.get(pos).getValue();
                if (pos == 0) {
                    mDropDownMenu.setTabText(2, "生产厂家");
                }
            }
            //网络请求
            isLoadMore = false;
            pageNum = 1;//设为默认加载第一页
            mData.clear();
            productsPresenter.getInventoryList(HwInfoUtils.getCustomerId(context), HwInfoUtils.getHospitalId(context), stockName, pageSize, pageNum);


        });
    }

    @Override
    protected void afterRequestPermission(int requestCode, boolean isAllGranted) {

    }


    @Override
    public void OnGetConfirmStockSuccess(ResponseBean responseBean) {
        if (commonShowDialog != null) {
            commonShowDialog.dismiss();
            commonShowDialog.closeLoding();
        }
        Intent intent = new Intent(context, ConfirmStockActivity.class);
        ConfirmStockEntity StockInfo = (ConfirmStockEntity) responseBean.pullData();
        intent.putExtra("StockInfo", StockInfo);
        if (str != null)
            intent.putStringArrayListExtra("str", str);
        startActivity(intent);
        finish();
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                try {
//                    Thread.sleep(3000);  //线程休眠3秒执行
//
//                    runOnUiThread(new Runnable() {
//                        @Override
//                        public void run() {
//                            if (commonShowDialog != null) {
//                                commonShowDialog.dismiss();
//                                commonShowDialog.closeLoding();
//                            }
//                            Intent intent = new Intent(context, ConfirmStockActivity.class);
//                            ConfirmStockEntity StockInfo = (ConfirmStockEntity) responseBean.pullData();
//                            intent.putExtra("StockInfo", StockInfo);
//                            if (str != null)
//                                intent.putStringArrayListExtra("str", str);
//                            startActivity(intent);
//                            finish();
//                        }
//                    });
//
//
//
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();

    }

    @Override
    public void onGetCategoryListSuccess(ResponseBean responseBean) {
        categoryList = (List<CategoryListEntity>) responseBean.pullData();
        if (categoryList == null)
            return;
        List<String> strings = new ArrayList<>();
        for (CategoryListEntity categoryListEntity : categoryList) {
            strings.add(categoryListEntity.getLabel());
        }
        selectTypeOne = strings.toArray(new String[strings.size()]);
        typeDtaPresenter.getManufacturerSel(macAddress, 1);
    }

    @Override
    public void onGetStockSelSuccess(ResponseBean responseBean) {

    }

    @Override
    public void onManufacturerSelSuccess(ResponseBean responseBean) {
        ManufacturerSelList = (List<CategoryListEntity>) responseBean.pullData();
        if (ManufacturerSelList == null)
            return;
        List<String> strings = new ArrayList<>();
        for (CategoryListEntity categoryListEntity : ManufacturerSelList) {
            strings.add(categoryListEntity.getLabel());
        }
        selectTypeThree = strings.toArray(new String[strings.size()]);
        typeDtaPresenter.getModelSel(macAddress, 1);
    }

    @Override
    public void onModelSelSuccess(ResponseBean responseBean) {
        ModelSelList = (List<CategoryListEntity>) responseBean.pullData();
        if (ModelSelList == null)
            return;
        List<String> strings = new ArrayList<>();
        for (CategoryListEntity categoryListEntity : ModelSelList) {
            strings.add(categoryListEntity.getLabel());
        }
        selectTypeTwo = strings.toArray(new String[strings.size()]);
        mDropDownMenu.setDropDownMenu(Arrays.asList(headers), initViewData(), contentView);

    }

    @Override
    public void onGetStockTypeSuccess(ResponseBean responseBean) {

    }

    @Override
    public void onGetProDtaSuccess(ResponseBean responseBean) {
        mSwipeLayout.setRefreshing(false);//完成刷新
//        responseBean.setClass(NewTakeStockEntity.class);
        InventoryListEntity stockEntity = (InventoryListEntity) responseBean.pullData();
        if (stockEntity == null)
            return;
        mTvAllNum.setText(String.valueOf(stockEntity.getTotal()));
        mData = stockEntity.getList();
        if (isLoadMore) {
            mAdapter.loadMoreComplete();//网络请求成功的话调用loadMoreComplete()
        }
        if (mData != null && mData.size() > 0) {//有了请求数据
            if (isLoadMore) {//为true时，是加载更多获取的数据
                mAdapter.addData(mData);//加载更多的数据，add进去
            } else {
                mAdapter.setNewData(mData);//进入或者上拉加载的数据(page=1),setnewdata
            }
            if (mData.size() == pageSize) {//获取的数据未10条时，说明还有下一页，page加1，以备下次请求
                pageNum++;
                mAdapter.setEnableLoadMore(true);//允许加载更多
            } else {
                mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
            }

        } else {
            if (pageNum == 1) {
                //数据得清空才会显示空布局
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
            }
            mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。

        }

    }

    @Override
    public void onGetInventoryListSuccess(ResponseBean responseBean) {
        mSwipeLayout.setRefreshing(false);//完成刷新
        InventoryListEntity stockEntity = (InventoryListEntity) responseBean.pullData();
        mData = stockEntity.getList();
        if (mTvAllNum != null)
            mTvAllNum.setText(String.valueOf(stockEntity.getTotal()));
        if (isLoadMore) {
            mAdapter.loadMoreComplete();//网络请求成功的话调用loadMoreComplete()
        }
        if (mData != null && mData.size() > 0) {//有了请求数据
            if (isLoadMore) {//为true时，是加载更多获取的数据
                mAdapter.addData(mData);//加载更多的数据，add进去
            } else {
                mAdapter.setNewData(mData);//进入或者上拉加载的数据(page=1),setnewdata
            }
            if (mData.size() == pageSize) {//获取的数据未10条时，说明还有下一页，page加1，以备下次请求
                pageNum++;
                mAdapter.setEnableLoadMore(true);//允许加载更多
            } else {
                mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
            }

        } else {
            if (pageNum == 1) {
                //数据得清空才会显示空布局
                mAdapter.getData().clear();
                mAdapter.notifyDataSetChanged();
            }
            mAdapter.loadMoreEnd(true);//若这次获得的数据没有10条，说明全部加载完毕。
        }
    }

    @Override
    public void onError(String msg) {

        ToastUtils.showText("后台错误！！！！！！");
        if (commonShowDialog != null) {
            commonShowDialog.dismiss();
            commonShowDialog.closeLoding();
        }

//        finish();

    }

    @Override
    public void onGetGoodsBySerno(ResponseBean responseBean) {

    }

    @Override
    public void onCheckInventorySuccess(ResponseBean responseBean) {


        if (commonShowDialog != null) {
            commonShowDialog.dismiss();
            commonShowDialog.closeLoding();
        }
        Intent intent = new Intent(context, ConfirmStockActivity.class);
        CheckInventoryEntity StockInfo = (CheckInventoryEntity) responseBean.pullData();
        intent.putExtra("StockInfo", StockInfo);
        if (str != null)
            intent.putStringArrayListExtra("str", str);
        startActivity(intent);
        finish();


    }

    //结算中弹框
    private void showJieSuanDia() {
        commonShowDialog = new CommonShowDialog(context);
        commonShowDialog.setContent("正在结算中");
        commonShowDialog.setContentHint("请稍候...");
        commonShowDialog.setImgShow(R.mipmap.icon_jiesuan);
        commonShowDialog.show();
        commonShowDialog.setCancelable(false);
        commonShowDialog.showLoding();

        faultcloseDia();
    }


    /**
     * 设置类型和数据源：
     * DropDownMenu.KEY对应类型（DropDownMenu中的常量，参考上述核心源码）
     * DropDownMenu.VALUE对应数据源：key不是TYPE_CUSTOM则传递string[],key是TYPE_CUSTOM类型则传递对应view
     */
    private List<HashMap<String, Object>> initViewData() {
        List<HashMap<String, Object>> viewDatas = new ArrayList<>();
        HashMap<String, Object> map;
        for (int i = 0; i < headers.length; i++) {
            map = new HashMap<String, Object>();
            map.put(DropDownMenu.KEY, types[i]);
            if (i == 0) {
                map.put(DropDownMenu.VALUE, selectTypeOne);
//                map.put(DropDownMenu.SELECT_POSITION, 1);

            } else if (i == 1) {
                map.put(DropDownMenu.VALUE, selectTypeTwo);
//                map.put(DropDownMenu.SELECT_POSITION, 0);

            } else if (i == 2) {
                map.put(DropDownMenu.VALUE, selectTypeThree);
//                map.put(DropDownMenu.SELECT_POSITION,2);

            }
            viewDatas.add(map);
        }
        return viewDatas;
    }


    @Override
    protected void onStop() {
        super.onStop();

    }

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {
        if (event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
            if (!isCloseDoor) {
                finish();
            } else {
                ToastUtils.showText(this, "请先关紧柜门！");
            }
            return true;
        } else {
            return super.dispatchKeyEvent(event);
        }
    }

    //event 关门
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCloseEvent(Event event) {
        if (event.getCode() == EventCode.EventClose) {
            showJieSuanDia();
        }
    }


    @Override
    protected void onDestroy() {
        if (commonShowDialog != null) {
            commonShowDialog.dismiss();
            commonShowDialog.closeLoding();
        }
        if (timer != null) timer.cancel();
        if (timercloseDia != null) timercloseDia.cancel();

        if (closeDoorHandler != null) closeDoorHandler.removeMessages(0);
        super.onDestroy();
    }

    CountDownTimer timer;

    public void startCountDownTimer() {
        TakeStockDtaActivity.this.runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (timer != null) timer.cancel();
                timer = new CountDownTimer(closeTime, 1000) {
                    @Override
                    public void onFinish() {
                        if (TakeStockDtaActivity.this == null || TakeStockDtaActivity.this.isFinishing() || mCancelled)
                            return;
                        if (tvTimer != null)
                            tvTimer.setText("即将关门盘点");
                    }

                    @Override
                    public void onTick(long millisUntilFinished) {
                        String time = MacUtils.formatTime(millisUntilFinished);
                        if (mCancelled)
                            return;
                        if (tvTimer != null)
                            tvTimer.setText(time + "后关门盘点");
                    }
                }.start();
            }
        });

    }

    /**
     * 容错弹框不关闭情况
     */
    private void faultcloseDia() {
        if (timercloseDia != null) {
            timercloseDia.cancel();
        }
        timercloseDia = new CountDownTimer(18000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {

            }

            @Override
            public void onFinish() {
                if (TakeStockDtaActivity.this == null || TakeStockDtaActivity.this.isFinishing() || mCancelled == true)
                    return;
                if (commonShowDialog != null && commonShowDialog.isShowing()) {
                    commonShowDialog.dismiss();
                    commonShowDialog.closeLoding();
                    Intent intent = new Intent(context, MainActivity.class);
                    startActivity(intent);
                    EventBusUtils.sendEvent(new Event(EventCode.showExitDia));

                    cancel();
                }

            }
        }.start();

    }

    @OnClick(R.id.bt_openDoor)
    public void onClick() {
        if (timercloseDia != null) timercloseDia.cancel();
        if (timer != null) timer.cancel();
        if (isPanMode) {

            closeDoor(100);
        } else {
            SmartBoxHelper.getInstance().openLightAndDoor(TakeStockDtaActivity.this, 100);
            closeDoorHandler.removeMessages(0);
            startCountDownTimer();
            closeDoorHandler.sendEmptyMessageDelayed(0, closeTime);
            bt_gm.setText("解除常开");
            bt_gm.setClickable(true);
        }
    }
}